﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.IO.Compression;

namespace IndexingHandler
{
    public class ZipHandler
    {
        public string fileToZip;
        public int maxFileLength;

        public ZipHandler(string fileName)
        {
            fileToZip = fileName;
        }

        public void RotateLogs()
        {
            FileInfo fileToCompress = new FileInfo(fileToZip);
            // Такого файла нет - выйдем
            if (!fileToCompress.Exists) return;
            // Размер меньше необходимого для индексации - выйдем
            if (fileToCompress.Length < maxFileLength) return;
            using (FileStream originalFileStream = fileToCompress.OpenRead())
            {
                if ((File.GetAttributes(fileToCompress.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
                {
                    string sYear = DateTime.Now.Year.ToString();
                    string sMonth = DateTime.Now.Month.ToString(); if (sMonth.Length == 1) sMonth = "0" + sMonth;
                    string sDay = DateTime.Now.Day.ToString(); if (sDay.Length == 1) sDay = "0" + sDay;
                    string sHour = DateTime.Now.Hour.ToString(); if (sHour.Length == 1) sHour = "0" + sHour;
                    string sMinute = DateTime.Now.Minute.ToString(); if (sMinute.Length == 1) sMinute = "0" + sMinute;
                    string sSecond = DateTime.Now.Second.ToString(); if (sSecond.Length == 1) sSecond = "0" + sSecond;
                    string zipFileName = fileToCompress.FullName.Replace(fileToCompress.Extension, "") + "_" + sYear + sMonth + sDay + "_" + sHour + sMinute + sSecond;
                    using (FileStream compressedFileStream = File.Create(zipFileName + ".gz"))
                    {
                        using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
                        {
                            originalFileStream.CopyTo(compressionStream);
                        }
                    }
                }
            }
            // Удалим оригинальный файл логов
            FileInfo fileToDelete = new FileInfo(fileToZip);
            // Такого файла нет - выйдем
            if (!fileToDelete.Exists) return;
            fileToDelete.Delete();
        }
    }
}
